//
//  LOStoreListViewController.m
//  renmingongshe
//
//  Created by macbook on 2017/10/25.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "LOStoreListViewController.h"
#import "LOGoodsListModel.h"
#import "LOGoodsTableViewCell.h"
#import "LOGoodsDetailViewController.h"

#define IMGADDSIZ (WIDTH*201/375-201)

@interface LOStoreListViewController ()<UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
{
    UITableView *_tab;
    UIView *_footerView;
    BOOL agree;
}
@property (weak, nonatomic) IBOutlet UIImageView *bgIma;
@property (weak, nonatomic) IBOutlet UIImageView *headIma;
@property (weak, nonatomic) IBOutlet UILabel *allNum;
@property (weak, nonatomic) IBOutlet UILabel *recNum;
@property (weak, nonatomic) IBOutlet UILabel *csNum;
@property (strong, nonatomic) UISearchBar *searchBar;
@property (assign, nonatomic) NSInteger pageNumber;
@property (strong, nonatomic) LOGoodsListModel *goodsModel;
@property (weak, nonatomic) IBOutlet UIButton *AllBtn;
@property (weak, nonatomic) IBOutlet UIButton *RecommdBtn;
@property (weak, nonatomic) IBOutlet UIButton *PriceBtn;
@property (weak, nonatomic) IBOutlet UIButton *NewBtn;
@property (weak, nonatomic) IBOutlet UIImageView *ArrowImg;
@property (weak, nonatomic) IBOutlet UIView *LineView;
@property (strong, nonatomic) NSDictionary *dic;
@property (copy, nonatomic) NSString *type;
@end

@implementation LOStoreListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _pageNumber = 1;
    _goodsModel = [[LOGoodsListModel alloc] init];
    _headIma.layer.borderColor = [[UIColor whiteColor]CGColor];
    _headIma.layer.borderWidth = 1.0f;
    [_headIma.layer setCornerRadius:3.0];
    _headIma.layer.masksToBounds = YES;
    [_AllBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self addBtn];
    [self createSearchBar];
    [self createBtn];
    [self createFooterView];
    [self createTableView];
    _type = @"all";
    [self getData];
}
- (void)addBtn
{
    if (IPHONE5S) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-40,_bgIma.height+IMGADDSIZ-40, 30, 30)];
        [btn setImage:[UIImage imageNamed:@"LOShare"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bgIma addSubview:btn];
        
        UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-40, btn.top-40, 30, 30)];
        [btn1 setImage:[UIImage imageNamed:@"LOCustom"] forState:UIControlStateNormal];
        [btn1 addTarget:self action:@selector(customCall:) forControlEvents:UIControlEventTouchUpInside];
        [_bgIma addSubview:btn1];
        
        UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-40, btn1.top-40, 30, 30)];
        [btn2 setImage:[UIImage imageNamed:@"LOStoreCollect"] forState:UIControlStateNormal];
        [btn2 addTarget:self action:@selector(storeCellect:) forControlEvents:UIControlEventTouchUpInside];
        [_bgIma addSubview:btn2];
    }else{
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-40,_bgIma.height+IMGADDSIZ-40, 30, 30)];
        [btn setImage:[UIImage imageNamed:@"LOShare"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bgIma addSubview:btn];
        
        UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(btn.left-40, _bgIma.height+IMGADDSIZ-40, 30, 30)];
        [btn1 setImage:[UIImage imageNamed:@"LOCustom"] forState:UIControlStateNormal];
        [btn1 addTarget:self action:@selector(customCall:) forControlEvents:UIControlEventTouchUpInside];
        [_bgIma addSubview:btn1];
        
        UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(btn1.left-40, _bgIma.height+IMGADDSIZ-40, 30, 30)];
        [btn2 setImage:[UIImage imageNamed:@"LOStoreCollect"] forState:UIControlStateNormal];
        [btn2 addTarget:self action:@selector(storeCellect:) forControlEvents:UIControlEventTouchUpInside];
        [_bgIma addSubview:btn2];
    }
}

- (void)createBtn
{
    _AllBtn.frame = CGRectMake(_AllBtn.origin.x, _bgIma.bottom+IMGADDSIZ+50+70, _AllBtn.width, _AllBtn.height);
    _AllBtn.tag = 111;
    [_AllBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _RecommdBtn.frame = CGRectMake(_RecommdBtn.origin.x, _AllBtn.origin.y, _RecommdBtn.width, _RecommdBtn.height);
    _RecommdBtn.tag = 222;
    [_RecommdBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _PriceBtn.frame = CGRectMake(_PriceBtn.origin.x, _AllBtn.origin.y, _PriceBtn.width, _PriceBtn.height);
    _PriceBtn.tag = 333;
    [_PriceBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _NewBtn.frame = CGRectMake(_NewBtn.origin.x, _AllBtn.origin.y, _NewBtn.width, _NewBtn.height);
    _NewBtn.tag = 444;
    [_NewBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _ArrowImg.frame = CGRectMake(_ArrowImg.origin.x, _bgIma.bottom+IMGADDSIZ+58+70, _ArrowImg.width, _ArrowImg.height);
}

- (void)BtnClick:(UIButton *)btn
{
    [_goodsModel.data removeAllObjects];
    switch (btn.tag) {
        case 111:
            _pageNumber = 1;
            _type = @"all";
            
            [self getData];
            [_AllBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [_RecommdBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_PriceBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_NewBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            break;
            
        case 222:
            _pageNumber = 1;
            _type = @"recommd";
            
            [self getData];
            [_RecommdBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [_AllBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_PriceBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_NewBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            break;
            
        case 333:
            _pageNumber = 1;
            _type = @"price";
            [_PriceBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [_RecommdBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_AllBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_NewBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            if (!agree) {
                [_ArrowImg setImage:[UIImage imageNamed:@"LOGoodsDown"]];
                
                [self getData];
            }else {
                [_ArrowImg setImage:[UIImage imageNamed:@"LOGoodsTop"]];
                
                [self getData];
            }
            agree = !agree;
            break;
            
        case 444:
            _pageNumber = 1;
            _type = @"new";
            
            [self getData];
            [_NewBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [_RecommdBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_PriceBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            [_AllBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
            break;
            
        default:
            break;
    }
}

- (void)getData
{
    [self.view loadingOnAnyView];
    
    if ([_type isEqualToString:@"all"]) {
        _dic = @{@"shopId":_shopId, @"page":[NSNumber numberWithInteger:_pageNumber], @"page_size":@"20", @"userToken":[Utils getUserToken]};
    }else if ([_type isEqualToString:@"recommd"]) {
        _dic = @{@"shopId":_shopId, @"page":[NSNumber numberWithInteger:_pageNumber], @"page_size":@"20", @"isRecom":@"1", @"userToken":[Utils getUserToken]};
    }else if ([_type isEqualToString:@"price"]) {
        _dic = @{@"shopId":_shopId, @"page":[NSNumber numberWithInteger:_pageNumber], @"page_size":@"20", @"msort":@"1" ,@"mdesc":[NSString stringWithFormat:@"%d", agree], @"userToken":[Utils getUserToken]};
    }else if ([_type isEqualToString:@"new"]){
        _dic = @{@"shopId":_shopId, @"page":[NSNumber numberWithInteger:_pageNumber], @"page_size":@"20", @"msort":@"2", @"mdesc":@"1", @"userToken":[Utils getUserToken]};
    }else{
        _dic = @{@"shopId":_shopId, @"page":[NSNumber numberWithInteger:_pageNumber], @"page_size":@"20", @"goodsName":_searchBar.text, @"userToken":[Utils getUserToken]};
    }
    
    [THWManager PostHttp:API(LOStoreDetail) Parameters:_dic Success:^(id responseObject) {
        [self.view removeAnyView];

        if ([_type isEqualToString:@"all"]) {
            //上半部分
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = responseObject[@"data"];
                [_headIma sd_setImageWithURL:[NSURL URLWithString:[Utils getImaSting:dic[@"shop_info"][@"shopImg"]]] placeholderImage:[UIImage imageNamed:@"NoStore"] options:SDWebImageRetryFailed];
                _allNum.text = [NSString stringWithFormat:@"%@",dic[@"shop_goodsNum"]];
                _csNum.text = [NSString stringWithFormat:@"%@",dic[@"shop_goodsNum"]];
                _recNum.text = [NSString stringWithFormat:@"%@",dic[@"shop_orderNum"]];
                self.titleLabel.text = [NSString stringWithFormat:@"%@",dic[@"shop_info"][@"shopName"]];
                //下面的tableview
                NSError *error;
                if ([responseObject[@"data"][@"shop_goods"] count] != 0) {
                    for (NSDictionary *dic in [responseObject objectForKey:@"data"][@"shop_goods"]) {
                        GoodsListModel *model = [[GoodsListModel alloc] initWithDictionary:dic error:&error];
                        [_goodsModel.data addObject:model];
                    }
                }else{
                    [self.view Message:@"暂无更多商品"];
                }
            }else{
                [self.view Message:responseObject[@"msg"]];
            }
            
        }else{
            //下面的tableview
            NSError *error;
            if ([responseObject[@"data"] count] != 0) {
                for (NSDictionary *dic in [responseObject objectForKey:@"data"]) {
                    GoodsListModel *model = [[GoodsListModel alloc] initWithDictionary:dic error:&error];
                    [_goodsModel.data addObject:model];
                }
            }else{
                [self.view Message:@"暂无更多商品"];
            }
        }
        [_tab reloadData];
        [_tab.mj_header endRefreshing];
        [_tab.mj_footer endRefreshing];
        
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}
- (IBAction)storeCellect:(id)sender {
}
- (IBAction)customCall:(id)sender {
}
- (IBAction)shareClick:(id)sender {
}

- (void)createSearchBar
{
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, _bgIma.bottom+IMGADDSIZ+10+70, WIDTH-20, 30)];
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.showsCancelButton = NO;
    _searchBar.placeholder = @"";
    _searchBar.delegate = self;
    for (UIView *subView in _searchBar.subviews) {
        if ([subView isKindOfClass:[UIView  class]]) {
            [[subView.subviews objectAtIndex:0] removeFromSuperview];
            if ([[subView.subviews objectAtIndex:0] isKindOfClass:[UITextField class]]) {
                UITextField *textField = [subView.subviews objectAtIndex:0];
                textField.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
                
                //设置默认文字颜色
                UIColor *color = [UIColor grayColor];
                [textField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"搜索商品/店铺" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName:color}]];
                //修改默认的放大镜图片
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 13, 13)];
                imageView.backgroundColor = [UIColor clearColor];
                imageView.image = [UIImage imageNamed:@"LineDownSearch"];
                textField.leftView = imageView;
            }
        }
    }
    [self.view addSubview:_searchBar];
}

#pragma mark-seacherDelegate
//回车键或者键盘的return触发
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    _pageNumber = 1;
    [_goodsModel.data removeAllObjects];
    _type = @"search";
    [self getData];
}

- (void)createFooterView
{
    _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
    _footerView.backgroundColor = RGB(232, 234, 234);
}

- (void)createTableView
{
    _tab = [[UITableView alloc] initWithFrame:CGRectMake(0, _bgIma.bottom+IMGADDSIZ+85+70, WIDTH, HEIGHT-(_bgIma.bottom+IMGADDSIZ+85+70))];
    _tab.delegate = self;
    _tab.dataSource = self;
    [_tab registerNib:[UINib nibWithNibName:@"LOGoodsTableViewCell" bundle:nil] forCellReuseIdentifier:@"LOGoodsTableViewCell"];
    _tab.showsVerticalScrollIndicator = NO;
    [_tab setTableFooterView:_footerView];
    [self.view addSubview:_tab];
    
    _tab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_goodsModel.data removeAllObjects];
        _pageNumber = 1;
        [self getData];
    }];
    _tab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pageNumber ++;
        [self getData];
    }];
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _goodsModel.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LOGoodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LOGoodsTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[LOGoodsTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"LOGoodsTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell cellConfigureModel:_goodsModel.data[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LOGoodsDetailViewController *detail = [[LOGoodsDetailViewController alloc] init];
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
